"use client";
import React, { useEffect, useState, useRef } from "react";
import { Button, Card, Divider, Image, message, Rate, Space, Tag, Modal, Avatar, Tooltip, Popover } from "antd";
import {
  getPostThumbNum, getPostThumbYesNo,
  postDoThumb,
  showMoodPost,
  getPostThumbYes,
  postDoComment,
  showMoodPostComment,
  postDoCommentThumb,
  getPostCommentThumbNum,
  getPostCommentThumbYesNo,
  getPostCommentNum,
  postDoCommentDelete,
  postDoPostDelete,
} from "@/api/moodPostController";
import {
  EyeOutlined,
  LikeFilled,
  LikeOutlined,
  MessageOutlined,
  ShareAltOutlined,
  SmileOutlined,
  DeleteOutlined,
  MoreOutlined,
  CopyOutlined,
  LinkOutlined,
} from "@ant-design/icons";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
import "dayjs/locale/zh-cn";
import { useSelector } from "react-redux";
import { RootState } from "@/stores";
import Picker from '@emoji-mart/react';
import data from '@emoji-mart/data';
import zh from '@emoji-mart/data/i18n/zh.json';

dayjs.extend(relativeTime);
dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.locale("zh-cn");

// 心情状态映射
const moodStateMap = [
  "开心", "兴奋", "平静", "轻松", "满足", "无聊", "困倦", "气炸", "暴怒", "难过",
  "沮丧", "郁闷", "焦虑", "烦躁", "疲惫", "失落", "无助", "委屈", "烦恼", "崩溃"
];

interface MoodPost {
  id: number;
  userAvatar: string;
  remarks: string;
  direction: string;
  userName: string;
  earlyTime: string;
  eveningTime: string;
  isWork: number;
  workLoad: number;
  moodScore: number;
  content: string;
  photoName: string;
  createTime: string;
  thumbNum?: number;
  isThumbed?: boolean;
  userAccount?: string;
  hottestComment?: any;
  moodState?: number;
}

interface MoodBankListProps {
  moodBankList: API.FunRiceUser[];
}

const imageActionBtnStyle: React.CSSProperties = {
  background: "transparent",
  border: "none",
  color: "#e5e6eb",
  fontWeight: 500,
  fontSize: 16,
  display: "flex",
  alignItems: "center",
  gap: 4,
  boxShadow: "none",
  padding: "4px 12px",
  borderRadius: 6,
  transition: "background 0.2s,color 0.2s",
  cursor: "pointer",
};

const imageActionBtnHoverStyle: React.CSSProperties = {
  background: "rgba(255,255,255,0.08)",
  color: "#fff",
};

const commentReplyTextStyle: React.CSSProperties = {
  color: "#888",
  fontWeight: 400,
  fontSize: 15,
  marginRight: 2,
};

const MoodBankList = ({ moodBankList }: MoodBankListProps) => {
  const [moodPosts, setMoodPosts] = useState<MoodPost[]>([]);
  const [loading, setLoading] = useState(false);
  const [thumbLoading, setThumbLoading] = useState<{ [key: number]: boolean }>(
    {},
  );
  const [thumbUsers, setThumbUsers] = useState<{ [postId: number]: any[] }>({});
  const loginUser = useSelector((state: RootState) => state.loginUser);

  // 评论弹窗相关状态
  const [commentModal, setCommentModal] = useState<{ visible: boolean; postId: number | null }>({ visible: false, postId: null });
  const [commentInput, setCommentInput] = useState("");
  const [commentList, setCommentList] = useState<any[]>([]);
  const [commentLoading, setCommentLoading] = useState(false);
  const [replyInfo, setReplyInfo] = useState<{ parentId?: number; replyUserId?: number; replyAccount?: string } | null>(null);
  const [commentSubmitting, setCommentSubmitting] = useState(false);
  const [commentThumbLoading, setCommentThumbLoading] = useState<{ [key: number]: boolean }>({});
  const [showEmoji, setShowEmoji] = useState(false);
  const [emojiHover, setEmojiHover] = useState(false);
  const [commentActive, setCommentActive] = useState(false);
  const [hasStartedTyping, setHasStartedTyping] = useState(false);
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const emojiBtnRef = useRef<HTMLSpanElement>(null);
  const emojiPickerRef = useRef<HTMLDivElement>(null);
  const commentBoxRef = useRef<HTMLDivElement>(null);

  const [commentThumbNum, setCommentThumbNum] = useState<{ [key: number]: number }>({});
  const [commentIsThumbed, setCommentIsThumbed] = useState<{ [key: number]: boolean }>({});
  const [commentNum, setCommentNum] = useState<{ [key: number]: number }>({});
  const [showAllComments, setShowAllComments] = useState<{ [key: number]: boolean }>({});

  // 新增：子评论框状态
  const [activeReplyId, setActiveReplyId] = useState<number | null>(null);
  const [replyInput, setReplyInput] = useState<string>("");
  const [replySubmitting, setReplySubmitting] = useState(false);
  const replyTextareaRef = useRef<HTMLTextAreaElement>(null);
  const [showReplyEmoji, setShowReplyEmoji] = useState(false);
  const replyEmojiBtnRef = useRef<HTMLSpanElement>(null);
  const replyEmojiPickerRef = useRef<HTMLDivElement>(null);
  const [replyActive, setReplyActive] = useState(false);

  // 新增：一级评论排序方式
  const [commentSortTypeMap, setCommentSortTypeMap] = useState<{ [postId: number]: 'latest' | 'hot' | 'floor' }>({});

  // 新增：控制显示删除按钮的评论id
  const [activeDeleteId, setActiveDeleteId] = useState<number | null>(null);

  // 新增：控制显示删除帖子按钮的帖子id
  const [activePostDeleteId, setActivePostDeleteId] = useState<number | null>(null);

  // 新增：每个帖子生成一个链接
  const [sharePopoverId, setSharePopoverId] = useState<number | null>(null);

  // 点击表情区外自动关闭
  useEffect(() => {
    if (!showEmoji) return;
    const handleClick = (e: MouseEvent) => {
      const btn = emojiBtnRef.current;
      const picker = emojiPickerRef.current;
      if (btn && btn.contains(e.target as Node)) return;
      if (picker && picker.contains(e.target as Node)) return;
      setShowEmoji(false);
    };
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, [showEmoji]);

  // 点击评论框外部自动还原
  useEffect(() => {
    const handleClick = (e: MouseEvent) => {
      const box = commentBoxRef.current;
      if (box && box.contains(e.target as Node)) return;
      // 只要评论框没有内容，就取消回复状态
      if (!commentInput.trim()) {
        setCommentActive(false);
        setReplyInfo(null);
      }
    };
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, [commentInput]);

  // 子评论表情区外自动关闭
  useEffect(() => {
    if (!showReplyEmoji) return;
    const handleClick = (e: MouseEvent) => {
      const btn = replyEmojiBtnRef.current;
      const picker = replyEmojiPickerRef.current;
      if (btn && btn.contains(e.target as Node)) return;
      if (picker && picker.contains(e.target as Node)) return;
      setShowReplyEmoji(false);
    };
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, [showReplyEmoji]);

  // 新增：点击页面其他地方关闭删除按钮
  useEffect(() => {
    const handleClick = (e: MouseEvent) => {
      const target = e.target as HTMLElement;
      if (!target.closest('.comment-action-more')) {
        setActiveDeleteId(null);
      }
    };
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, []);

  // 新增：点击页面其他地方关闭帖子删除按钮
  useEffect(() => {
    const handleClick = (e: MouseEvent) => {
      const target = e.target as HTMLElement;
      if (!target.closest('.post-action-more')) {
        setActivePostDeleteId(null);
      }
    };
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, []);

  const fetchMoodPosts = async () => {
    setLoading(true);
    try {
      const res = await showMoodPost({});
      //@ts-ignore
      if (res.code === 0 && res.data) {
        const posts = Array.isArray(res.data) ? res.data : [];
        // 获取每个帖子的点赞数、评论数和最热评论
        const postsWithData = await Promise.all(
          posts.map(async (post) => {
            try {
              const thumbRes = await getPostThumbNum(post.id);
              const thumbYesNoRes = await getPostThumbYesNo(post.id);
              const commentNumRes = await getPostCommentNum(post.id);
              setCommentNum(prev => ({ ...prev, [post.id]: commentNumRes.data || 0 }));

              // 获取评论并找到最热评论
              let hottestComment = null;
              if (commentNumRes.data > 0) {
                 try {
                   const commentRes = await showMoodPostComment(post.id);
                   if (commentRes.code === 0 && Array.isArray(commentRes.data)) {
                     const comments = commentRes.data;
                     // 找到一级评论
                     const rootComments = comments.filter((item: any) => !item.parentId || item.parentId === 0);
                     if (rootComments.length > 0) {
                        // 根据回复数排序找到最热评论 (回复数最多，然后按最新排序)
                        const sortedRootComments = [...rootComments].sort((a, b) => {
                           const aChildren = comments.filter((item: any) => item.parentId === a.id).length;
                           const bChildren = comments.filter((item: any) => item.parentId === b.id).length;
                           if (bChildren !== aChildren) {
                              return bChildren - aChildren;
                           }
                           return new Date(b.createTime).getTime() - new Date(a.createTime).getTime(); // 如果回复数相同，按最新排序
                        });
                        hottestComment = sortedRootComments[0];
                         // 预加载最热评论的点赞信息
                         if(hottestComment) {
                            fetchCommentThumbInfo(hottestComment.id);
                         }
                     }
                   }
                 } catch (commentError) {
                    console.error(`Failed to fetch comments for post ${post.id}:`, commentError);
                 }
              }


              return {
                ...post,
                thumbNum: thumbRes.data || 0,
                isThumbed:  thumbYesNoRes.data > 0 ,
                hottestComment: hottestComment // 存储最热评论
              };
            } catch (error) {
              console.error(
                `Failed to fetch data for post ${post.id}:`,
                error,
              );
              setCommentNum(prev => ({ ...prev, [post.id]: 0 }));
              return {
                ...post,
                thumbNum: 0,
                isThumbed: false,
                hottestComment: null // 没有评论或获取失败
              };
            }
          }),
        );
        setMoodPosts(postsWithData);
      } else {
        message.error("获取心情动态失败");
      }
    } catch (error) {
      message.error("获取心情动态失败");
    } finally {
      setLoading(false);
    }
  };

  const fetchThumbUsers = async (postId: number) => {
    if (thumbUsers[postId]) return;
    try {
      const res = await getPostThumbYes(postId);
      console.log('点赞用户返回', postId, res.data);
      if (res.code === 0 && Array.isArray(res.data)) {
        //@ts-ignore
        setThumbUsers(prev => ({ ...prev, [postId]: res.data }));
      } else {
        setThumbUsers(prev => ({ ...prev, [postId]: [] }));
      }
    } catch {
      setThumbUsers(prev => ({ ...prev, [postId]: [] }));
    }
  };

  useEffect(() => {
    fetchMoodPosts();
  }, [moodBankList]);

  useEffect(() => {
    moodPosts.forEach(post => {
      fetchThumbUsers(post.id);
    });
  }, [moodPosts]);

  const handleThumb = async (postId: number) => {
    if (thumbLoading[postId]) return;

    setThumbLoading((prev) => ({ ...prev, [postId]: true }));
    try {
      const res = await postDoThumb(postId);
      if (res.code === 0) {
        setMoodPosts((prev) =>
          prev.map((post) => {
            if (post.id === postId) {
              const newThumbNum = (post.thumbNum || 0) + res.data;
              return {
                ...post,
                thumbNum: newThumbNum,
                isThumbed: res.data > 0,
              };
            }
            return post;
          }),
        );
      } else {
        message.error(res.message || "操作失败");
      }
    } catch (error) {
      message.error("操作失败");
    } finally {
      setThumbLoading((prev) => ({ ...prev, [postId]: false }));
    }
  };

  const formatTime = (time: string) => {
    // 转为北京时间（东八区）
    return dayjs.utc(time).tz("Asia/Shanghai").fromNow();
  };

  const getWorkStatus = (isWork: number) => {
    switch (isWork) {
      case 0:
        return "上班";
      case 1:
        return "学习";
      case 2:
        return "休息";
      default:
        return "未知";
    }
  };

  // 打开评论弹窗
  const openCommentModal = async (postId: number) => {
    setCommentModal({ visible: true, postId });
    setReplyInfo(null);
    setCommentInput("");
    await fetchCommentList(postId);
    setShowAllComments({});
    setCommentSortTypeMap(prev => ({ ...prev, [postId]: 'latest' }));
  };
  // 关闭评论弹窗
  const closeCommentModal = () => {
    setCommentModal({ visible: false, postId: null });
    setReplyInfo(null);
    setCommentInput("");
    setCommentList([]);
    setShowAllComments({});
  };
  // 获取评论点赞数和状态
  const fetchCommentThumbInfo = async (commentId: number) => {
    try {
      const [numRes, yesNoRes] = await Promise.all([
        getPostCommentThumbNum(commentId),
        getPostCommentThumbYesNo(commentId),
      ]);
      setCommentThumbNum(prev => ({ ...prev, [commentId]: numRes.data || 0 }));
      setCommentIsThumbed(prev => ({ ...prev, [commentId]: (yesNoRes.data as number) > 0 }));
    } catch {
      setCommentThumbNum(prev => ({ ...prev, [commentId]: 0 }));
      setCommentIsThumbed(prev => ({ ...prev, [commentId]: false }));
    }
  };
  // 获取评论列表（重构，严格按表结构）
  const fetchCommentList = async (postId: number) => {
    setCommentLoading(true);
    try {
      const res = await showMoodPostComment(postId);
      if (res.code === 0 && Array.isArray(res.data)) {
        const list = res.data;
        // 一级评论
        const roots = list.filter((item: any) => !item.parentId || item.parentId === 0);
        // 二级评论挂到一级评论下
        roots.forEach((root: any) => {
          root.children = list.filter((item: any) => item.parentId === root.id);
        });
        setCommentList(roots);
        // 获取所有评论点赞数和状态
        const allComments: any[] = [];
        roots.forEach(root => {
          allComments.push(root);
          if (root.children && root.children.length > 0) {
            root.children.forEach((child: any) => allComments.push(child));
          }
        });
        allComments.forEach(comment => {
          fetchCommentThumbInfo(comment.id);
        });
      } else {
        setCommentList([]);
      }
    } catch {
      setCommentList([]);
    } finally {
      setCommentLoading(false);
    }
  };
  // 提交评论（一级/二级）
  const handleSubmitComment = async () => {
    if (!commentInput.trim()) {
      message.warning("请输入评论内容");
      return;
    }
    if (!loginUser?.id) {
      message.error("请先登录");
      return;
    }
    if (!commentModal.postId) {
      message.error("评论异常，请刷新重试");
      return;
    }
    setCommentSubmitting(true);
    try {
      const parentId = replyInfo?.parentId ?? 0;
      const replyUserId = replyInfo?.replyUserId ?? 0;
      const replyAccount = replyInfo?.replyAccount ? replyInfo.replyAccount : '';
      const res = await postDoComment(
        Number(commentModal.postId),
        commentInput,
        Number(parentId),
        Number(replyUserId),
        replyAccount
      );
      if (res.code === 0) {
        message.success("评论成功");
        setCommentInput("");
        setReplyInfo(null);
        await fetchCommentList(commentModal.postId);
        // 新增：评论成功后立即刷新评论数
        if (commentModal.postId) {
          const commentNumRes = await getPostCommentNum(commentModal.postId);
          setCommentNum(prev => ({ ...prev, [commentModal.postId!]: commentNumRes.data || 0 }));
        }
      } else {
        message.error(res.message || "评论失败");
      }
    } catch (e: any) {
      message.error(e.message || "评论失败");
    } finally {
      setCommentSubmitting(false);
    }
  };
  // 点赞评论
  const handleCommentThumb = async (commentId: number) => {
    if (commentThumbLoading[commentId]) return;
    setCommentThumbLoading((prev) => ({ ...prev, [commentId]: true }));
    try {
      const res = await postDoCommentThumb(commentId);
      if (res.code === 0) {
        await fetchCommentThumbInfo(commentId);
      } else {
        message.error(res.message || "操作失败");
      }
    } catch (e: any) {
      message.error(e.message || "操作失败");
    } finally {
      setCommentThumbLoading((prev) => ({ ...prev, [commentId]: false }));
    }
  };
  // 回复评论
  const handleReply = (parentId: number, replyUserId: number, replyAccount: string) => {
    setReplyInfo({ parentId, replyUserId, replyAccount });
    setCommentInput("");
    setCommentActive(true);
  };

  // 评论区渲染（重构，严格按表结构）
   //二级评论挂到一级评论下 样式设置
  const commentActionStyle: React.CSSProperties = {
    color: "#888",
    fontWeight: 400,
    fontSize: 12,
    background: "none",
    border: "none",
    boxShadow: "none",
    display: "flex",
    alignItems: "center",
    gap: 4,
    padding: "0 8px 0 0",
    cursor: "pointer",
    userSelect: "none"
  };
  const renderCommentList = (list: any[], postId: number, postUserAccount?: string, showAll?: boolean) => {
    // 排序
    let sortedList = [...list];
    const commentSortType = commentSortTypeMap[postId] || 'latest';
    if (commentSortType === 'latest' || commentSortType === 'floor') {
      sortedList.sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime());
    } else if (commentSortType === 'hot') {
      sortedList.sort((a, b) => (b.children?.length || 0) - (a.children?.length || 0));
    }
    // 展开全部 or 只显示前3条
    const displayList = showAll ? sortedList : sortedList.slice(0, 3);
    return (
      <div>
        {/* 评论总数+排序按钮区 */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
          <span style={{ color: '#222', fontSize: 14, fontWeight: 500 }}>
            {commentNum[postId] || 0}个评论
          </span>
          <div style={{ display: 'flex', alignItems: 'center', gap: 0, fontSize: 14, fontWeight: 400 }}>
            <span
              style={{
                color: commentSortType === 'hot' ? '#1677ff' : '#222',
                cursor: commentSortType === 'hot' ? 'default' : 'pointer',
                padding: '0 4px',
                background: 'none',
                transition: 'color 0.2s',
                marginRight: 8,
                userSelect: 'none',
              }}
              onClick={() => commentSortType !== 'hot' && setCommentSortTypeMap(prev => ({ ...prev, [postId]: 'hot' }))}
            >
              最热
            </span>
            <span style={{ color: '#e5e6eb', margin: '0 4px', userSelect: 'none' }}>|</span>
            <span
              style={{
                color: commentSortType === 'latest' ? '#1677ff' : '#222',
                cursor: commentSortType === 'latest' ? 'default' : 'pointer',
                padding: '0 4px',
                background: 'none',
                transition: 'color 0.2s',
                marginLeft: 8,
                userSelect: 'none',
              }}
              onClick={() => commentSortType !== 'latest' && setCommentSortTypeMap(prev => ({ ...prev, [postId]: 'latest' }))}
            >
              最新
            </span>
            <span style={{ color: '#e5e6eb', margin: '0 4px', userSelect: 'none' }}>|</span>
            <span
              style={{
                color: commentSortType === 'floor' ? '#1677ff' : '#222',
                cursor: commentSortType === 'floor' ? 'default' : 'pointer',
                padding: '0 4px',
                background: 'none',
                transition: 'color 0.2s',
                marginLeft: 8,
                userSelect: 'none',
              }}
              onClick={() => commentSortType !== 'floor' && setCommentSortTypeMap(prev => ({ ...prev, [postId]: 'floor' }))}
            >
              楼层
            </span>
          </div>
        </div>
        {displayList.map(item => (
          <div key={item.id} style={{ display: 'flex', alignItems: 'flex-start', marginBottom: 16, position: 'relative' }}>
            <Avatar src={item.userAvatar} size={36} style={{ marginRight: 12 }} />
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <span style={{ fontWeight: 400, fontSize: 14 }}>{item.remarks || item.userName}</span>
                {/* 一级评论作者标签 */}
                {item.userAccount === postUserAccount && (
                  <span style={{
                    marginLeft: 10,
                    color: '#1677ff',
                    fontSize: 12,
                    background: '#eaf4ff',
                    borderRadius: 0,
                    padding: '0 6px',
                    marginRight: 2,
                    fontWeight: 500,
                    lineHeight: '18px',
                    display: 'inline-block',
                  }}>作者</span>
                )}
                <span style={{ color: '#888', fontSize: 13, marginLeft: 8 }}>{item.direction}</span>
              </div>
              <div style={{ fontWeight: 400, fontSize: 14, color: '#222', margin: '4px 0' }}>{item.comment}</div>
              <div style={{ display: 'flex', alignItems: 'center', gap:6, marginTop: 4, position: 'relative', justifyContent: 'space-between' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ color: '#888', fontSize: 12 }}>{formatTime(item.createTime)}</span>
                <span style={commentActionStyle}>
                  <Button
                    type="text"
                    icon={
                      commentIsThumbed[item.id] ? (
                        <LikeFilled style={{ color: "#1677ff", fontSize: 12, marginRight: 4 }} />
                      ) : (
                        <LikeOutlined style={{ fontSize: 12, marginRight: 4 }} />
                      )
                    }
                    onClick={() => handleCommentThumb(item.id)}
                    loading={commentThumbLoading[item.id]}
                    style={{
                      ...commentActionStyle,
                      color: commentIsThumbed[item.id] ? "#1677ff" : "#222",
                      fontWeight: 500,
                      fontSize: 15,
                      display: "flex",
                      alignItems: "center",
                      padding: 0,
                      background: "none",
                      border: "none",
                      boxShadow: "none"
                    }}
                  >
                    <span style={commentActionStyle}>
                      {commentThumbNum[item.id] && commentThumbNum[item.id] > 0 ? commentThumbNum[item.id] : "点赞"}
                    </span>
                  </Button>
                </span>
                <span style={commentActionStyle} onClick={() => {
                  if (activeReplyId === item.id) {
                    setActiveReplyId(null);
                    setReplyInput("");
                  } else {
                    setActiveReplyId(item.id);
                    setReplyInput("");
                  }
                }}>
                  <MessageOutlined style={{ fontSize: 12, color: activeReplyId === item.id ? '#1677ff' : undefined }} />
                  <span style={{ marginLeft: 2, fontSize: 12, color: activeReplyId === item.id ? '#1677ff' : undefined }}>
                    {activeReplyId === item.id ? '取消评论' : '评论'}
                  </span>
                </span>
                </div>
                {/* 删除按钮交互 */}
                {((loginUser?.userAccount && loginUser.userAccount === postUserAccount) || (loginUser?.userAccount && loginUser.userAccount === item.userAccount)) && (
                  <div className="comment-action-more" style={{ position: 'absolute', right: 0, top: '50%', transform: 'translateY(-50%)' }}>
                    {activeDeleteId === item.id ? (
                      <Button
                        type="text"
                        icon={<DeleteOutlined style={{ fontSize: 14, color: '#666' }} />}
                        style={{
                          display: 'flex',
                          alignItems: 'center',
                          fontWeight: 400,
                          fontSize: 14,
                          padding: '5px 12px',
                          width: '92px',
                          justifyContent: 'flex-start',
                          color: '#666',
                          background: '#fff',
                          boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
                          borderRadius: 4
                        }}
                        onClick={() => handleDeleteComment(postId, item.id)}
                      >
                        删除
                      </Button>
                    ) : (
                      <Button
                        type="text"
                        icon={<MoreOutlined rotate={90} style={{ fontSize: 16 }} />}
                        style={{ color: '#8a919f', fontSize: 16, padding: 0, width: 24, minWidth: 24, height: 24 }}
                        onClick={e => {
                          e.stopPropagation();
                          setActiveDeleteId(item.id);
                        }}
                      />
                    )}
                  </div>
                )}
              </div>
              {/* 子评论框，仅一级评论下展示 */}
              {activeReplyId === item.id && (
                <div style={{ background: '#f7f8fa', borderRadius: 8, margin: '12px 0 0 0', padding: 12, boxShadow: '0 1px 4px rgba(0,0,0,0.03)' }}>
                  <div style={{ display: 'flex', alignItems: 'flex-start' }}>
                    <Avatar src={loginUser?.userAvatar} size={32} style={{ marginRight: 10, marginTop: 2 }} />
                    <div style={{ flex: 1, position: 'relative' }}>
                      <div
                        style={{
                          border: '1px solid #e5e6eb',
                          borderRadius: 4,
                          background: '#fff',
                          padding: 0,
                          transition: 'border 0.2s',
                          width: '100%',
                        }}
                        onClick={() => replyTextareaRef.current?.focus()}
                      >
                        <textarea
                          value={replyInput}
                          onChange={e => setReplyInput(e.target.value)}
                          placeholder={`回复 @${item.remarks || item.userName}`}
                          style={{
                            width: '100%',
                            border: 'none',
                            outline: 'none',
                            resize: 'none',
                            background: 'transparent',
                            padding: '10px',
                            fontSize: 15,
                            fontWeight: 400,
                            lineHeight: 1.6,
                            overflowY: 'auto',
                          }}
                          maxLength={1000}
                          rows={2}
                          ref={replyTextareaRef}
                          onFocus={() => setReplyActive(true)}
                          onBlur={() => setReplyActive(false)}
                        />
                        {showReplyEmoji && (
                          <div
                            ref={replyEmojiPickerRef}
                            style={{
                              position: 'absolute',
                              left: 0,
                              top: '100%',
                              zIndex: 9999,
                              width: 320,
                              background: '#fff',
                            }}
                          >
                            <Picker
                              data={data}
                              locale="zh"
                              i18n={zh}
                              onEmojiSelect={handleReplyEmojiSelect}
                              theme="light"
                              previewPosition="none"
                              skinTonePosition="none"
                            />
                          </div>
                        )}
                        <div
                          style={{
                            width: '100%',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'space-between',
                            background: 'transparent',
                            border: 'none',
                            boxShadow: 'none',
                            padding: '0 0 0 0',
                            boxSizing: 'border-box',
                            overflow: 'hidden',
                          }}
                        >
                          <div style={{ display: 'flex', alignItems: 'center' }}>
                            <div style={{ position: 'relative' }}>
                              <span
                                ref={replyEmojiBtnRef}
                                style={{
                                  display: 'flex',
                                  alignItems: 'center',
                                  cursor: 'pointer',
                                  color: showReplyEmoji ? '#1677FF' : '#222',
                                  fontSize: 14,
                                  fontWeight: 500,
                                  gap: 4,
                                  padding: '2px 6px',
                                  borderRadius: 6,
                                  transition: 'background 0.2s, color 0.2s',
                                  background: 'transparent',
                                  zIndex: 10,
                                  height: 32,
                                  minWidth: 32
                                }}
                                onClick={() => setShowReplyEmoji(v => !v)}
                              >
                                <div style={{
                                  width: 24,
                                  height: 24,
                                  display: 'flex',
                                  alignItems: 'center',
                                  justifyContent: 'center',
                                  borderRadius: '50%',
                                  background: 'transparent',
                                  overflow: 'hidden',
                                }}>
                                  <SmileOutlined style={{ fontSize: 18, color: showReplyEmoji ? '#1677FF' : '#222' }} />
                                </div>
                              </span>
                            </div>
                          </div>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                            <span style={{ color: replyInput.length > 1000 ? '#ff4d4f' : '#888', fontSize: 13 }}>
                              {replyInput.length} / 1000
                            </span>
                            <Tooltip
                              title={<span style={{ fontSize: 14 }}>Ctrl + Enter</span>}
                              placement="topRight"
                              overlayStyle={{
                                maxWidth: 120,
                                wordBreak: 'keep-all',
                                whiteSpace: 'nowrap',
                                fontSize: 14,
                                zIndex: 1000,
                              }}
                            >
                              <Button
                                type="primary"
                                style={{
                                  borderRadius: 6,
                                  minWidth: 60,
                                  background: !replyInput.trim() ? '#a0cfff' : '#1677ff',
                                  color: '#fff',
                                  border: 'none',
                                  boxShadow: 'none',
                                  fontWeight: 500,
                                  fontSize: 12,
                                  transition: 'background 0.2s',
                                }}
                                loading={replySubmitting}
                                onClick={() => handleSubmitReply(item.id, item.userId, item.userName)}
                                disabled={!replyInput.trim()}
                              >
                                发送
                              </Button>
                            </Tooltip>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              )}
              {/* 二级评论 */}
              {item.children && item.children.length > 0 && (
                <div style={{ marginTop: 8 }}>
                  {/* 先排序 */}
                  {[...item.children].sort((a, b) => new Date(a.createTime).getTime() - new Date(b.createTime).getTime()).map((child: any) => (
                    <div key={child.id} style={{ display: 'flex', alignItems: 'flex-start', marginBottom: 8, marginLeft: 5 }}>
                      {/* 头像 */}
                      <Avatar src={child.userAvatar} size={32} style={{ marginRight: 8, flexShrink: 0 }} />
                      {/* 内容区 */}
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ minWidth: 0 }}>
                          <span style={{ display: 'inline', fontWeight: 400, fontSize: 14, marginRight: 8, whiteSpace: 'nowrap' }}>{child.remarks || child.userName}</span>
                          {child.userAccount === postUserAccount && (
                            <span style={{
                              display: 'inline',
                              marginLeft: 3,
                              color: '#1677ff',
                              fontSize: 12,
                              background: '#eaf4ff',
                              borderRadius: 0,
                              padding: '0 6px',
                              marginRight: 2,
                              fontWeight: 500,
                              lineHeight: '18px',
                              whiteSpace: 'nowrap'
                            }}>作者</span>
                          )}
                          {(child.replyAccount && child.replyAccount !== (item.remarks || item.userName)) && (
                            <>
                              <span style={{   fontWeight: 400, fontSize: 14, margin: '0 2px', whiteSpace: 'nowrap' }}>回复 </span>
                              <span style={{color: '#1677ff',display: 'inline', fontSize: 14,margin: '0 3px', whiteSpace: 'nowrap' }}>@{child.replyAccount} </span>
                            </>
                          )}
                          <span style={{
                            color: '#888',
                          }}>: </span>
                          <span style={{
                            display: 'inline',
                            fontWeight: 400,
                            fontSize: 14,
                            color: '#222',
                            wordBreak: 'break-all',
                            whiteSpace: 'pre-wrap'
                          }}>{child.comment}</span>
                        </div>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 2, marginLeft: 0, position: 'relative', justifyContent: 'space-between' }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                          <span style={{ color: '#888', fontSize: 12 }}>{formatTime(child.createTime)}</span>
                          <span style={commentActionStyle}>
                            <Button
                              type="text"
                              icon={
                                commentIsThumbed[child.id] ? (
                                  <LikeFilled style={{ color: "#1677ff", fontSize: 12, marginRight: 4 }} />
                                ) : (
                                  <LikeOutlined style={{ fontSize: 12, marginRight: 4 }} />
                                )
                              }
                              onClick={() => handleCommentThumb(child.id)}
                              loading={commentThumbLoading[child.id]}
                              style={{
                                ...commentActionStyle,
                                color: commentIsThumbed[child.id] ? "#1677ff" : "#222",
                                fontWeight: 500,
                                fontSize: 15,
                                display: "flex",
                                alignItems: "center",
                                padding: 0,
                                background: "none",
                                border: "none",
                                boxShadow: "none"
                              }}
                            >
                              <span style={commentActionStyle}>
                                {commentThumbNum[child.id] && commentThumbNum[child.id] > 0 ? commentThumbNum[child.id] : "点赞"}
                              </span>
                            </Button>
                          </span>
                          <span style={commentActionStyle} onClick={() => {
                            if (activeReplyId === child.id) {
                              setActiveReplyId(null);
                              setReplyInput("");
                            } else {
                              setActiveReplyId(child.id);
                              setReplyInput("");
                            }
                          }}>
                            <MessageOutlined style={{ fontSize: 12, color: activeReplyId === child.id ? '#1677ff' : undefined }} />
                            <span style={{ marginLeft: 2, fontSize: 12, color: activeReplyId === child.id ? '#1677ff' : undefined }}>
                              {activeReplyId === child.id ? '取消回复' : '回复'}
                            </span>
                          </span>
                          </div>
                          {/* 删除按钮交互 */}
                          {((loginUser?.userAccount && loginUser.userAccount === postUserAccount) || (loginUser?.userAccount && loginUser.userAccount === child.userAccount)) && (
                            <div className="comment-action-more" style={{ position: 'absolute', right: 0, top: '50%', transform: 'translateY(-50%)' }}>
                              {activeDeleteId === child.id ? (
                                <Button
                                  type="text"
                                  icon={<DeleteOutlined style={{ fontSize: 14, color: '#666' }} />}
                                  style={{
                                    display: 'flex',
                                    alignItems: 'center',
                                    fontWeight: 400,
                                    fontSize: 14,
                                    padding: '5px 12px',
                                    width: '92px',
                                    justifyContent: 'flex-start',
                                    color: '#666',
                                    background: '#fff',
                                    boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
                                    borderRadius: 4
                                  }}
                                  onClick={() => handleDeleteComment(postId, child.id)}
                                >
                                  删除
                                </Button>
                              ) : (
                                <Button
                                  type="text"
                                  icon={<MoreOutlined rotate={90} style={{ fontSize: 16 }} />}
                                  style={{ color: '#8a919f', fontSize: 16, padding: 0, width: 24, minWidth: 24, height: 24 }}
                                  onClick={e => {
                                    e.stopPropagation();
                                    setActiveDeleteId(child.id);
                                  }}
                                />
                              )}
                            </div>
                          )}
                        </div>
                        {/* 子评论框，仅二级评论下展示 */}
                        {activeReplyId === child.id && (
                          <div style={{ background: '#f7f8fa', borderRadius: 8, margin: '12px 0 0 0', padding: 12, boxShadow: '0 1px 4px rgba(0,0,0,0.03)' }}>
                            <div style={{ display: 'flex', alignItems: 'flex-start' }}>
                              <Avatar src={loginUser?.userAvatar} size={32} style={{ marginRight: 10, marginTop: 2 }} />
                              <div style={{ flex: 1, position: 'relative' }}>
                                <div
                                  style={{
                                    border: '1px solid #e5e6eb',
                                    borderRadius: 4,
                                    background: '#fff',
                                    padding: 0,
                                    transition: 'border 0.2s',
                                    width: '100%',
                                  }}
                                  onClick={() => replyTextareaRef.current?.focus()}
                                >
                                  <textarea
                                    value={replyInput}
                                    onChange={e => setReplyInput(e.target.value)}
                                    placeholder={`回复 @${child.remarks || child.userName}`}
                                    style={{
                                      width: '100%',
                                      border: 'none',
                                      outline: 'none',
                                      resize: 'none',
                                      background: 'transparent',
                                      padding: '10px',
                                      fontSize: 15,
                                      fontWeight: 400,
                                      lineHeight: 1.6,
                                      overflowY: 'auto',
                                    }}
                                    maxLength={1000}
                                    rows={2}
                                    ref={replyTextareaRef}
                                    onFocus={() => setReplyActive(true)}
                                    onBlur={() => setReplyActive(false)}
                                  />
                                  {showReplyEmoji && (
                                    <div
                                      ref={replyEmojiPickerRef}
                                      style={{
                                        position: 'absolute',
                                        left: 0,
                                        top: '100%',
                                        zIndex: 9999,
                                        width: 320,
                                        background: '#fff',
                                      }}
                                    >
                                      <Picker
                                        data={data}
                                        locale="zh"
                                        i18n={zh}
                                        onEmojiSelect={handleReplyEmojiSelect}
                                        theme="light"
                                        previewPosition="none"
                                        skinTonePosition="none"
                                      />
                                    </div>
                                  )}
                                  <div
                                    style={{
                                      width: '100%',
                                      display: 'flex',
                                      alignItems: 'center',
                                      justifyContent: 'space-between',
                                      background: 'transparent',
                                      border: 'none',
                                      boxShadow: 'none',
                                      padding: '0 0 0 0',
                                      boxSizing: 'border-box',
                                      overflow: 'hidden',
                                    }}
                                  >
                                    <div style={{ display: 'flex', alignItems: 'center' }}>
                                      <div style={{ position: 'relative' }}>
                                        <span
                                          ref={replyEmojiBtnRef}
                                          style={{
                                            display: 'flex',
                                            alignItems: 'center',
                                            cursor: 'pointer',
                                            color: showReplyEmoji ? '#1677FF' : '#222',
                                            fontSize: 14,
                                            fontWeight: 500,
                                            gap: 4,
                                            padding: '2px 6px',
                                            borderRadius: 6,
                                            transition: 'background 0.2s, color 0.2s',
                                            background: 'transparent',
                                            zIndex: 10,
                                            height: 32,
                                            minWidth: 32
                                          }}
                                          onClick={() => setShowReplyEmoji(v => !v)}
                                        >
                                          <div style={{
                                            width: 24,
                                            height: 24,
                                            display: 'flex',
                                            alignItems: 'center',
                                            justifyContent: 'center',
                                            borderRadius: '50%',
                                            background: 'transparent',
                                            overflow: 'hidden',
                                          }}>
                                            <SmileOutlined style={{ fontSize: 18, color: showReplyEmoji ? '#1677FF' : '#222' }} />
                                          </div>
                                        </span>
                                      </div>
                                    </div>
                                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                                      <span style={{ color: replyInput.length > 1000 ? '#ff4d4f' : '#888', fontSize: 13 }}>
                                        {replyInput.length} / 1000
                                      </span>
                                      <Tooltip
                                        title={<span style={{ fontSize: 14 }}>Ctrl + Enter</span>}
                                        placement="topRight"
                                        overlayStyle={{
                                          maxWidth: 120,
                                          wordBreak: 'keep-all',
                                          whiteSpace: 'nowrap',
                                          fontSize: 14,
                                          zIndex: 1000,
                                        }}
                                      >
                                        <Button
                                          type="primary"
                                          style={{
                                            borderRadius: 6,
                                            minWidth: 60,
                                            background: !replyInput.trim() ? '#a0cfff' : '#1677ff',
                                            color: '#fff',
                                            border: 'none',
                                            boxShadow: 'none',
                                            fontWeight: 500,
                                            fontSize: 12,
                                            transition: 'background 0.2s',
                                          }}
                                          loading={replySubmitting}
                                          onClick={() => handleSubmitReply(child.parentId, child.userId, child.userName)}
                                          disabled={!replyInput.trim()}
                                        >
                                          发送
                                        </Button>
                                      </Tooltip>
                                    </div>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
    );
  };

  const handleEmojiSelect = (emoji: any) => {
    const textarea = textareaRef.current;
    if (textarea) {
      const start = textarea.selectionStart;
      const end = textarea.selectionEnd;
      const newValue = commentInput.slice(0, start) + emoji.native + commentInput.slice(end);
      setCommentInput(newValue);
      setTimeout(() => {
        textarea.focus();
        textarea.setSelectionRange(start + emoji.native.length, start + emoji.native.length);
      }, 0);
    }
  };

  const handleReplyEmojiSelect = (emoji: any) => {
    const textarea = replyTextareaRef.current;
    if (textarea) {
      const start = textarea.selectionStart;
      const end = textarea.selectionEnd;
      const newValue = replyInput.slice(0, start) + emoji.native + replyInput.slice(end);
      setReplyInput(newValue);
      setTimeout(() => {
        textarea.focus();
        textarea.setSelectionRange(start + emoji.native.length, start + emoji.native.length);
      }, 0);
    }
  };

  const handleSubmitReply = async (parentId: number, replyUserId: number, replyAccount: string) => {
    if (!replyInput.trim()) {
      message.warning("请输入评论内容");
      return;
    }
    if (!loginUser?.id) {
      message.error("请先登录");
      return;
    }
    if (!commentModal.postId) {
      message.error("评论异常，请刷新重试");
      return;
    }
    setReplySubmitting(true);
    try {
      const res = await postDoComment(
        Number(commentModal.postId),
        replyInput,
        Number(parentId),
        Number(replyUserId),
        replyAccount || ''
      );
      if (res.code === 0) {
        message.success("评论成功");
        setReplyInput("");
        setActiveReplyId(null);
        await fetchCommentList(commentModal.postId);
        // 评论成功后立即刷新评论数
        const commentNumRes = await getPostCommentNum(commentModal.postId);
        setCommentNum(prev => ({ ...prev, [commentModal.postId!]: commentNumRes.data || 0 }));
      } else {
        message.error(res.message || "评论失败");
      }
    } catch (e: any) {
      message.error(e.message || "评论失败");
    } finally {
      setReplySubmitting(false);
    }
  };

  const handleCommentBtnClick = (postId: number) => {
    if (commentModal.visible && commentModal.postId === postId) {
      closeCommentModal();
      setShowAllComments(prev => ({ ...prev, [postId]: false }));
      setActiveReplyId(null);
    } else {
      openCommentModal(postId);
      setShowAllComments(prev => ({ ...prev, [postId]: false }));
    }
  };

  const handleDeleteComment = async (postId: number, commentId: number) => {
    Modal.confirm({
      title: '确定要删除这条评论吗？',
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          const res = await postDoCommentDelete(postId, commentId);
          if (res.code === 0) {
            message.success('删除成功');
            await fetchCommentList(postId);
            // 刷新评论数
            const commentNumRes = await getPostCommentNum(postId);
            setCommentNum(prev => ({ ...prev, [postId]: commentNumRes.data || 0 }));
          } else {
            message.error(res.message || '删除失败');
          }
        } catch (e: any) {
          message.error(e.message || '删除失败');
        }
      }
    });
  };

  // 删除帖子
  const handleDeletePost = async (post: MoodPost) => {
    if (loginUser?.userAccount !== post.userAccount) {
      message.error('非作者无权限删除');
      return;
    }
    Modal.confirm({
      title: '确定要删除这条帖子吗？',
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          const res = await postDoPostDelete(post.id);
          if (res.code === 0) {
            message.success('删除成功');
            await fetchMoodPosts();
          } else {
            message.error(res.message || '删除失败');
          }
        } catch (e: any) {
          message.error(e.message || '删除失败');
        }
      }
    });
  };

  const handleCopyLink = (postId: number) => {
    const url = `${window.location.origin}/mood/${postId}`;
    navigator.clipboard.writeText(url);
    message.success('链接已复制');
    setSharePopoverId(null);
  };

  return (
    <div className="mood-bank-list">
      <Space direction="vertical" style={{ width: "100%" }} size={5}>
        {moodPosts.map((post, index) => (
          <Card
            key={post.id}
            style={{
              width: "100%",
              borderRadius: "8px",
              boxShadow: "0 2px 8px rgba(0,0,0,0.08)",
              position: 'relative'
            }}
            bodyStyle={{
              padding: "22px",
            }}
          >
            {/* 帖子右上角操作按钮 */}
            <div className="post-action-more" style={{ position: 'absolute', top: 18, right: 18, zIndex: 10 }}>
              {activePostDeleteId === post.id ? (
                <Button
                  type="text"
                  icon={<DeleteOutlined style={{ fontSize: 14, color: '#666' }} />}
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    fontWeight: 400,
                    fontSize: 14,
                    padding: '5px 12px',
                    width: '92px',
                    justifyContent: 'flex-start',
                    color: '#666',
                    background: '#fff',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
                    borderRadius: 4
                  }}
                  onClick={() => handleDeletePost(post)}
                >
                  删除
                </Button>
              ) : (
                <Button
                  type="text"
                  icon={<MoreOutlined rotate={90} style={{ fontSize: 16, color: '#1677ff' }} />}
                  style={{ color: '#1677ff', fontSize: 16, padding: 0, width: 24, minWidth: 24, height: 24 }}
                  onClick={e => {
                    e.stopPropagation();
                    setActivePostDeleteId(post.id);
                  }}
                />
              )}
            </div>
            <div style={{ display: "flex", marginBottom: 12 }}>
              <div
                style={{
                  width: 48,
                  height: 48,
                  borderRadius: 50,
                  overflow: "hidden",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  background: "#fff",
                }}
              >
                <img
                  src={post.userAvatar}
                  alt="avatar"
                  width={48}
                  height={48}
                  style={{
                    width: "48px",
                    height: "48px",
                    borderRadius: "50%",
                  }}
                />
              </div>
              <div
                style={{
                  marginLeft: 8, // 增加头像与右侧信息的间距
                  display: 'flex',
                  flexDirection: 'column',
                  justifyContent: 'center',
                  gap: 4 // 增加昵称与remark等信息的垂直间距
                }}
              >
                <div
                  style={{
                    fontSize: "15px",
                    fontWeight: 500,
                    color: "#262626",
                  }}
                >
                  {post.remarks || post.userName}
                </div>
                <div
                  style={{
                    marginTop: 0,
                    color: "#595959",
                    fontSize: 13,
                  }}
                >
                  {post.direction} @{post.userName} ·{" "}
                  {formatTime(post.createTime)}
                </div>
              </div>
            </div>

            <div style={{ marginBottom: 12 }}>
              <Space size={[0, 8]} wrap>
                {/* 工作状态标签 */}
                <Tag style={{
                  backgroundColor: '#f7f8fa',
                  color: '#888',
                  border: '1px solid #e5e6eb',
                  borderRadius: 16,
                  padding: '4px 12px',
                  fontSize: 14,
                }}>
                  {getWorkStatus(post.isWork)}
                </Tag>
                {/* 起床时间标签 */}
                <Tag style={{
                  backgroundColor: '#f7f8fa',
                  color: '#888',
                  border: '1px solid #e5e6eb',
                  borderRadius: 16,
                  padding: '4px 12px',
                  fontSize: 14,
                }}>
                  {post.earlyTime?.split("T")[1].slice(0, 5)} 起床
                </Tag>
                {/* 预计晚休时间标签 */}
                <Tag style={{
                  backgroundColor: '#f7f8fa',
                  color: '#888',
                  border: '1px solid #e5e6eb',
                  borderRadius: 16,
                  padding: '4px 12px',
                  fontSize: 14,
                }}>
                  {post.eveningTime?.split("T")[1].slice(0, 5)} 晚休
                </Tag>
              </Space>
            </div>

            <div
              style={{
                marginBottom: 12,
                fontSize: 15,
                lineHeight: 1.6,
                color: "#262626",
                whiteSpace: "pre-line",
              }}
            >
              {post.content}
            </div>
 {/* // 帖子多图片预览展示 */}
            {post.photoName && (
              <div style={{ marginBottom: 12, display: 'flex', gap: 16, flexWrap: 'wrap' }}>
                <Image.PreviewGroup>
                  {post.photoName.split(',').map((url, idx) => {
                    const imageCount = post.photoName.split(',').length;
                    // 根据图片数量动态调整宽度
                    const imageWidth = imageCount === 1 ? 200 : (imageCount === 2 ? 200 : 150);
                    return (
                      <Image
                        key={idx}
                        src={url}
                        alt={`心情图片${idx + 1}`}
                        width={imageWidth}
                        height={imageWidth}
                        style={{ 
                          borderRadius: 8,
                          objectFit: 'cover'  // 保持图片比例
                        }}
                        preview={{
                          mask: (
                            <span
                              style={{
                                display: "flex",
                                alignItems: "center",
                                gap: 6,
                              }}
                            >
                              <EyeOutlined style={{ fontSize: 18 }} />
                              预览
                            </span>
                          ),
                          maskClassName: "custom-image-mask",
                        }}
                      />
                    );
                  })}
                </Image.PreviewGroup>
              </div>
            )}

            {/* 最热评论预览 */}
            {post.hottestComment && (
              <div style={{
                marginTop: 12,
                marginBottom: 12,
                padding: '12px',
                background: '#FBFBFB',
                borderRadius: 8,
                display: 'flex',
                alignItems: 'flex-start',
                gap: 8
              }}>
                 {/* 内容区 */}
                 <div style={{ flex: 1, minWidth: 0 }}>
                    <span style={{ fontWeight: 400, fontSize: 14, color: '#222', marginRight: 4 }}>好友的解决方法：</span>
                    
                    <span style={{
                       fontSize: 14,
                       color: '#222',
                       overflow: 'hidden',
                       textOverflow: 'ellipsis',
                       display: '-webkit-box',
                       WebkitLineClamp: 1, // 限制一行
                       WebkitBoxOrient: 'vertical',
                       wordBreak: 'break-all',
                    }}>
                       <Avatar src={post.hottestComment.userAvatar} size={30.4} /> {post.hottestComment.remarks || post.hottestComment.userName}<span style={{ color: '#888', fontSize: 14 }}> : </span>{post.hottestComment.comment}
                    </span>
                 </div>
              </div>
            )}

            {/* 心情状态标签和点赞用户头像/文本 */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8, marginRight: 12, minHeight: 32 }}>
              {/* 心情状态标签 */}
              {post.moodState !== undefined && post.moodState >= 0 && post.moodState < moodStateMap.length && (
                 <Tag
                style={{
                     backgroundColor: '#f7f8fa', // 浅灰色背景
                     color: '#1677FF', // 蓝色文字
                     borderRadius: 16, // 圆角
                     padding: '4px 12px', // 增加内边距
                     fontSize: 12, // 字体大小
                     border: 'none', // 移除边框
                     display: 'inline-block', // 行内块显示
                     lineHeight: '18px', // 行高
                     height: 'auto', // 高度自适应
                   }}
                 >
                   <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                     <div style={{ width: 18, height: 18, borderRadius: '50%', background: 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                       <img src="/assets/moostate.svg" alt="mood state icon" style={{ width: 12, height: 12 }} /> {/* 替换为SVG图标 */}
                     </div>
                     <span>{moodStateMap[post.moodState]}</span>
                   </div>
                 </Tag>
              )}

              {/* 点赞用户头像/文本 */}
              {(post.isThumbed || (thumbUsers[post.id] && thumbUsers[post.id].length > 0)) && (
                <div style={{ display: "flex", alignItems: "center" }}>
                  {/* 新增：如果当前用户点赞了并且不在thumbUsers列表中，则显示当前用户头像 */}
                  {post.isThumbed && loginUser?.userAvatar && !(thumbUsers[post.id] || []).some(user => user.userAccount === loginUser.userAccount) && (
                     <Tooltip title={ loginUser.userAccount} key={loginUser.userAccount}>
                        <Avatar
                           src={loginUser.userAvatar}
                           size={24}
                           style={{
                             border: 'none',
                             marginLeft: 0, // 当前用户头像放在第一个
                             zIndex: ((thumbUsers[post.id] || []).length) + 1, // 确保当前用户头像在最上层
                             boxShadow: 'none'
                           }}
                         />
                     </Tooltip>
                  )}
                  {/* 显示其他点赞用户头像 */}
                  {(thumbUsers[post.id] || []).map((user, idx) => (
                    <Tooltip title={user.remarks || user.userAccount} key={user.userAccount}>
                      <Avatar
                        src={user.userAvatar}
                        size={24}
                        style={{
                          border: 'none',
                          marginLeft: (post.isThumbed && loginUser?.userAccount !== user.userAccount) || idx > 0 ? -12 : 0, // 如果当前用户头像已显示，或者不是第一个用户，则设置负边距
                          zIndex: (thumbUsers[post.id] || []).length - idx,
                          boxShadow: 'none'
                        }}
                      />
                    </Tooltip>
                  ))}
                <span style={{ marginLeft: 8, color: "#888", fontSize: 15 }}>赞过</span>
              </div>
            )}
            </div>

            {/* 心情卡片底部按钮间距 */}
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                width: "100%",
                padding: "0 30px 0px 30px",
                background: "#fff"
              }}
            >
              <div style={{ display: "flex", alignItems: "center", flex: 1, justifyContent: "flex-start" }}>
                <Popover
                  open={sharePopoverId === post.id}
                  onOpenChange={open => setSharePopoverId(open ? post.id : null)}
                  content={
                    <Button
                      type="text"
                      icon={<LinkOutlined />}
                      onClick={() => handleCopyLink(post.id)}
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        padding: '4px 12px',
                        fontSize: 15,
                        borderRadius: 6,
                        color: '#666',
                        background: '#fff',
                        boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
                        minWidth: 0,
                        minHeight: 0,
                      }}
                    >
                      复制链接
                    </Button>
                  }
                  trigger="click"
                  placement="bottom"
                  overlayInnerStyle={{
                    padding: 0,
                    minWidth: 'auto',
                    boxShadow: 'none',
                    background: 'transparent',
                    borderRadius: 6,
                  }}
                >
                <Button
                  type="text"
                  icon={<ShareAltOutlined style={{ fontSize: 14 }} />}
                  style={{
                    color: "#222",
                    fontWeight: 500,
                    fontSize: 14,
                    display: "flex",
                    alignItems: "center",
                    background: 'none',
                    boxShadow: 'none',
                    transition: 'none',
                  }}
                >
                  分享
                </Button>
                </Popover>
              </div>
              <div style={{ display: "flex", alignItems: "center", flex: 1, justifyContent: "center" }}>
                <Button
                  type="text"
                  icon={
                    commentModal.visible && commentModal.postId === post.id ? (
                      <MessageOutlined style={{ fontSize: 14, color: '#1677ff' }} />
                    ) : (
                      <MessageOutlined style={{ fontSize: 14 }} />
                    )
                  }
                  style={{
                    color: commentModal.visible && commentModal.postId === post.id ? '#1677ff' : '#222',
                    fontWeight: 500,
                    fontSize: 14,
                    display: "flex",
                    alignItems: "center",
                    background: 'none',
                    boxShadow: 'none',
                    transition: 'none',
                  }}
                  onClick={() => handleCommentBtnClick(post.id)}
                >
                  {commentModal.visible && commentModal.postId === post.id
                    ? '收起评论'
                    : (commentNum[post.id] && commentNum[post.id] > 0 ? commentNum[post.id] : "评论")}
                </Button>
              </div>
              <div style={{ display: "flex", alignItems: "center", flex: 1, justifyContent: "flex-end" }}>
                <Button
                  type="text"
                  icon={
                    post.isThumbed ? (
                      <LikeFilled style={{ color: "#1677ff", fontSize: 14 }} />
                    ) : (
                      <LikeOutlined style={{ fontSize: 15 }} />
                    )
                  }
                  onClick={() => handleThumb(post.id)}
                  loading={thumbLoading[post.id]}
                  style={{
                    color: post.isThumbed ? "#1677ff" : "#222",
                    fontWeight: 500,
                    fontSize: 14,
                    display: "flex",
                    alignItems: "center",
                    background: 'none',
                    boxShadow: 'none',
                    transition: 'none',
                  }}
                >
                  {post.thumbNum && post.thumbNum > 0 ? post.thumbNum : "点赞"}
                </Button>
              </div>
            </div>
            {/* 评论弹窗 */}
            {commentModal.visible && commentModal.postId === post.id && (
              <div style={{ marginTop: 18 }}>
                <div style={{ position: 'relative', margin: '0 0 14px 0' }}>
                  <div
                    style={{
                      position: 'absolute',
                      left: '50%',
                      top: '-8px',
                      transform: 'translateX(-50%)',
                      width: 0,
                      height: 0,
                      borderLeft: '8px solid transparent',
                      borderRight: '8px solid transparent',
                      borderBottom: '8px solid #f0f0f0',
                      zIndex: 1,
                      background: 'none',
                      boxShadow: 'none',
                    }}
                  />
                </div>
                <div style={{ display: 'flex', alignItems: 'flex-start', marginBottom: 12 }}>
                  <Avatar src={loginUser?.userAvatar} size={40} style={{ marginRight: 12, marginTop: 2 }} />
                  <div style={{ flex: 1, position: 'relative' }}>
                    <div
                      ref={commentBoxRef}
                      style={{
                        position: 'relative',
                        width: '100%',
                        background: '#f7f8fa',
                        borderRadius: 8,
                        margin: '0 0 0 0',
                        padding: 12,
                        boxShadow: '0 1px 4px rgba(0,0,0,0.03)',
                        display: 'flex',
                        alignItems: 'flex-start',
                      }}
                    >
                      <div
                        style={{
                          border: '1px solid #e5e6eb',
                          borderRadius: 6,
                          background: '#fff',
                          padding: 0,
                          transition: 'border 0.2s',
                          width: '100%',
                          boxSizing: 'border-box',
                        }}
                        onClick={() => textareaRef.current?.focus()}
                      >
                        <textarea
                          value={commentInput}
                          onChange={e => {
                            setCommentInput(e.target.value);
                            setHasStartedTyping(true);
                          }}
                          placeholder={replyInfo ? `回复 @${replyInfo.replyAccount}` : "平等表达，友善交流"}
                          style={{
                            width: '100%',
                            minHeight: (commentActive ? 2: 1) * 24 + 24,
                            maxHeight: (commentActive ? 4 : 2) * 24 + 24,
                            border: 'none',
                            outline: 'none',
                            color: '#222',
                            fontWeight: 400,
                            resize: 'none',
                            background: 'transparent',
                            boxSizing: 'border-box',
                            lineHeight: 1.6,
                            fontSize: 15,
                            padding: '12px',
                            boxShadow: 'none',
                            borderBottom: 'none',
                            borderBottomLeftRadius: 0,
                            borderBottomRightRadius: 0,
                            overflowY: 'auto',
                          }}
                          maxLength={1000}
                          rows={commentActive ? 2 : 1}
                          onInput={e => {
                            const textarea = e.currentTarget;
                            textarea.style.height = 'auto';
                            let newHeight = Math.min(textarea.scrollHeight, (commentActive ? 4 : 2) * 24 + 24);
                            textarea.style.height = newHeight + 'px';
                            if (textarea.scrollHeight > newHeight + 1) {
                              textarea.style.overflowY = 'auto';
                            } else {
                              textarea.style.overflowY = 'hidden';
                            }
                          }}
                          onFocus={() => setCommentActive(true)}
                          onBlur={() => {
                            if (!commentInput.trim()) {
                              setCommentActive(false);
                              const textarea = textareaRef.current;
                              if (textarea) {
                                textarea.style.height = 'auto';
                                textarea.style.height = '48px';
                                textarea.style.overflowY = 'hidden';
                              }
                            } else if (textareaRef.current) {
                              if (textareaRef.current.scrollHeight > textareaRef.current.clientHeight + 1) {
                                textareaRef.current.style.overflowY = 'auto';
                              } else {
                                textareaRef.current.style.overflowY = 'hidden';
                              }
                            }
                          }}
                          onKeyDown={e => {
                            if (e.ctrlKey && e.key === 'Enter') {
                              e.preventDefault();
                              handleSubmitComment();
                            }
                          }}
                          ref={textareaRef}
                        />
                        <div
                          style={{
                            width: '100%',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'space-between',
                            background: 'transparent',
                            border: 'none',
                            boxShadow: 'none',
                            padding: '8px 12px',
                            boxSizing: 'border-box',
                          }}
                        >
                          <div style={{ display: 'flex', alignItems: 'center', position: 'relative' }}>
                            <span
                              ref={emojiBtnRef}
                              style={{
                                display: 'flex',
                                alignItems: 'center',
                                cursor: 'pointer',
                                color: emojiHover ? '#1677FF' : '#222',
                                fontSize: 14,
                                fontWeight: 500,
                                gap: 4,
                                padding: '2px 6px',
                                borderRadius: 6,
                                transition: 'background 0.2s, color 0.2s',
                                background: 'transparent',
                                zIndex: 10,
                                height: 32,
                                minWidth: 32
                              }}
                              onMouseEnter={() => setEmojiHover(true)}
                              onMouseLeave={() => setEmojiHover(false)}
                              onClick={() => setShowEmoji(true)}
                            >
                              <div style={{
                                width: 24,
                                height: 24,
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                borderRadius: '50%',
                                background: 'transparent',
                                overflow: 'hidden',
                              }}>
                                <SmileOutlined style={{ fontSize: 18, color: emojiHover ? '#1677FF' : '#222' }} />
                              </div>
                            </span>
                            {showEmoji && (
                              <div
                                ref={emojiPickerRef}
                                style={{
                                  position: 'absolute',
                                  left: 0,
                                  top: '110%',
                                  zIndex: 9999,
                                  width: 320,
                                  background: '#fff',
                                  border: 'none',
                                  boxShadow: 'none',
                                  borderRadius: 0,
                                  padding: 0,
                                  margin: 0,
                                }}
                                onMouseDown={e => e.preventDefault()}
                              >
                                <Picker
                                  data={data}
                                  locale="zh"
                                  i18n={zh}
                                  onEmojiSelect={handleEmojiSelect}
                                  theme="light"
                                  previewPosition="none"
                                  skinTonePosition="none"
                                />
                              </div>
                            )}
                          </div>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                            <span style={{ color: commentInput.length > 1000 ? '#ff4d4f' : '#888', fontSize: 13 }}>
                              {commentInput.length} / 1000
                            </span>
                            <Tooltip
                              title={<span style={{ fontSize: 14 }}>Ctrl + Enter</span>}
                              placement="topRight"
                              overlayStyle={{
                                maxWidth: 120,
                                wordBreak: 'keep-all',
                                whiteSpace: 'nowrap',
                                fontSize: 14,
                                zIndex: 1000,
                              }}
                            >
                              <Button
                                type="primary"
                                style={{
                                  borderRadius: 6,
                                  minWidth: 60,
                                  background: !commentInput.trim() ? '#a0cfff' : '#1677ff',
                                  color: '#fff',
                                  border: 'none',
                                  boxShadow: 'none',
                                  fontWeight: 500,
                                  fontSize: 12,
                                  transition: 'background 0.2s',
                                }}
                                loading={commentSubmitting}
                                onClick={handleSubmitComment}
                                disabled={!commentInput.trim()}
                              >
                                发送
                              </Button>
                            </Tooltip>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div style={{ maxHeight: 'none' }}>
                  {commentLoading ? (
                    <div style={{ textAlign: "center", color: "#888" }}>加载中...</div>
                  ) : commentList.length === 0 ? (
                    <div style={{ textAlign: "center", color: "#888" }}>暂无评论</div>
                  ) : (
                    <>
                      {renderCommentList(
                        commentList,
                        commentModal.postId!,
                        post.userAccount,
                        showAllComments[post.id]
                      )}
                      {commentList.length > 3 && !showAllComments[post.id] && (
                        <div style={{ textAlign: "center", marginTop: 12 }}>
                          <Button
                            type="link"
                            style={{ fontSize: 15, color: '#1677ff' }}
                            onClick={() => setShowAllComments(prev => ({ ...prev, [post.id]: true }))}
                          >
                            查看全部 {commentNum[post.id] || commentList.length} 条评论 <span style={{ fontSize: 12 }}>▼</span>
                          </Button>
                        </div>
                      )}
                      {/* 只有在全部评论已展开时才显示"已显示全部评论" */}
                      {commentList.length >= 1 && (showAllComments[post.id] || commentList.length <= 3) && (
                        <div style={{ textAlign: 'center', margin: '20px 0', display: 'flex', alignItems: 'center', height: 24, minHeight: 24 }}>
                          <div style={{ flexGrow: 1, height: 1, minHeight: 1, background: '#e5e6eb', margin: '0 10px' }} />
                          <span style={{ color: '#888', fontSize: 14, fontWeight: 400, lineHeight: '24px', padding: 0, margin: 0 }}>已显示全部评论</span>
                          <div style={{ flexGrow: 1, height: 1, minHeight: 1, background: '#e5e6eb', margin: '0 10px' }} />
                        </div>
                      )}
                    </>
                  )}
                </div>
              </div>
            )}
          </Card>
        ))}
      </Space>
    </div>
  );
};

export default MoodBankList;
